<?php
	require('config.php');
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n--------------------------\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n收到微信回调通知:".date('Y-m-d H:i:s')."\r\n", FILE_APPEND);
	//$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	$msg = array();
	$postStr = file_get_contents('php://input');
	$msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n返回全部信息：".json_encode($msg)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n返回格式    ：".$msg."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n返回数据条数：".count($msg)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\nappid       ：".$msg['appid']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n支付结果    ：".$msg['result_code']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n商户号      ：".$msg['mch_id']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n订单信息    ：".$msg['attach']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n交易单号    ：".$msg['transaction_id']."\r\n", FILE_APPEND);
	// file_put_contents("tsxx_WxPay.txt", "\r\n".var_export($postObj,true)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay_jf_order.txt", "\r\n--------------------------\r\n", FILE_APPEND);
	if($msg['result_code']=='SUCCESS')
	{
		$time=date('Y-m-d H:i:s');
		$time2=time();
		//收到支付成功信息
		$json=explode(',',$msg['attach']);//获取orderId列表
		$user_id=$json[0];
		$goods_id=$json[1];
		$address=$json[2];
		$sql="select * from `".$oto."_users` where `userId`='".$user_id."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$user_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		//$msg['total_fee']=$msg['total_fee']/100;
		// if($pay_money!=$msg['total_fee'])
		// {
		// 	$user_lin_money=$msg['total_fee'];
		// 	$tarde_no=$msg['trade_no'];
		// 	$user_money_lin2=$user_info[0]['userMoney']+$user_lin_money;
		// 	$sql="update ".$oto."_users set userMoney='{$user_money_lin2}' where userId='{$user_id}'";
		// 	$result=$db->query($sql);
		// 	$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`) VALUES ('$user_id','$tarde_no','$user_lin_money','$user_money_lin2','$time2','1','3','支付宝退款','1')";
  //           $result=$db->query($sql);
		// 	echo "success";
		// 	exit();
		// }
		$sql="select * from `".$oto."_orders` where `orderunique`='".$msg['transaction_id']."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$order_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		if(isset($order_info))
		{
			echo "success";
			exit();
		}
		$pay_way=2;
		$sql="select * from `".$oto."_integral` where `goodsId`='".$goods_id."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$goods_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		$sql="select * from `".$oto."_user_address` where `addressId`='".$address."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$address_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		
		//验证通过，开始减库存，加销量，减积分，增加积分消费记录，增加订单，增加商户提醒
		$hgoodsStock=$goods_info[0]['goodsStock']-1;
		$hsaleCount=$goods_info[0]['saleCount']+1;
		if($hgoodsStock==0)//开始减库存，加销量
		{
			$sql="update ".$oto."_integral set goodsStock='{$hgoodsStock}',saleCount='{$hsaleCount}',isSale='0' where goodsId='{$goods_id}'";
			$result=$db->query($sql);
		}
		else if($hgoodsStock>0)
		{
			$sql="update ".$oto."_integral set goodsStock='{$hgoodsStock}',saleCount='{$hsaleCount}' where goodsId='{$goods_id}'";
			$result=$db->query($sql);
		}
		
		//增加订单
		$orderNo=microtime(true)*10000;//订单号
		$areaId1=$address_info[0]['areaId1'];
		$areaId2=$address_info[0]['areaId2'];
		$areaId3=$address_info[0]['areaId3'];
		$orderStatus=0;
		$totalMoney=$goods_info[0]['marketPrice'];
		$deliverType=0;//配送方式
		$userName=$address_info[0]['userName'];
		$communityId=$address_info[0]['communityId'];
			$dizhi='';
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId1']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$sheng[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId2']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$shi[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId3']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$xian[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_communitys` where `communityId`='".$address_info[0]['communityId']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$jiedao[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$dizhi=$sheng[0]['areaName'].$shi[0]['areaName'].$xian[0]['areaName'].$jiedao[0]['communityName'].$address_info[0]['address'];
		$userAddress=$dizhi;
		$userPhone=$address_info[0]['userPhone'];
		$orderScore=$totalMoney;
		$requireTime=0;//期望送达时间
		$createTime=date('Y-m-d H:i:s');//下单时间
		$time=time();
		$orderunique=floor(microtime(true)*1000);//是否同一批下单
		$orderunique=$msg['transaction_id'];
		$needPay=$totalMoney;//应付金额
		$sql="INSERT INTO ".$oto."_orders (`orderNo`,`areaId1`,`areaId2`,`areaId3`,`orderStatus`,`totalMoney`,`deliverType`,`userId`,`userName`,`communityId`,`userAddress`,`userPhone`,`orderScore`,`orderRemarks`,`createTime`,`orderunique`,`needPay`,`orderType`,`payType`,`isPay`,`shopId`) VALUES ('$orderNo','$areaId1','$areaId2','$areaId3','$orderStatus','$totalMoney','$deliverType','$user_id','$userName','$communityId','$userAddress','$userPhone','$orderScore','','$createTime','$orderunique','$needPay','4','$pay_way','1','0')";
        $result2=$db->query($sql);//插入order表
        //file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
        $sql="select * from `".$oto."_orders` where `orderNo`='".$orderNo."' and `userId`='{$user_id}' and `orderunique`='{$orderunique}'";
		$result=$db->query($sql);//查询刚插进去的orderId
		while($row=$result->fetch_assoc()){
			$order[0]=$row;//将取得的所有数据赋值给person_info数组
		}
		$orderId=$order[0]['orderId'];
		$sql="INSERT INTO ".$oto."_log_orders (`orderId`,`logContent`,`logUserId`,`logType`,`logTime`) VALUES ('$orderId','下单成功','$user_id','0','$createTime')";
            		$result=$db->query($sql);
		$goodsPrice=$totalMoney;
		$goodsName=$goods_info[0]['goodsName'];
		$goodsThums=$goods_info[0]['goodsImg'];
        $sql="INSERT INTO ".$oto."_order_goods (`orderId`,`goodsId`,`goodsNums`,`goodsPrice`,`goodsName`,`goodsThums`,`goodsGroupId`) VALUES ('$orderId','$goods_id','1','$goodsPrice','$goodsName','$goodsThums','0')";
        $result=$db->query($sql);//插入order对应的order_goods表
		//增加订单end
        //file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
		//增加积分消费记录

		//增加余额消费记录
		$huserMoney=$user_info[0]['userMoney'];
	    $sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`totalscore`,`time`,`IncDec`,`type`,`payWay`,`remark`) VALUES ('$user_id','$orderNo','$totalMoney','$huserMoney','$time2','0','1','2','微信支付')";
	    $result=$db->query($sql);
		//echo "success";
		response.getWriter().write(XMLUtil.setXML("SUCCESS", "OK")); 
		// 告诉微信服务器，我收到信息了，不要在调用回调action了
	}
?>